package org.poptest.util;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * License: MIT
 * User: alan
 * Date: 21/01/11
 * Time: 23:56
 */
public final class ClassUtils {

    private static final Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new HashMap<Class<?>, Class<?>>();


    static {
        primitiveWrapperTypeMap.put(Boolean.class, boolean.class);
        primitiveWrapperTypeMap.put(Byte.class, byte.class);
        primitiveWrapperTypeMap.put(Character.class, char.class);
        primitiveWrapperTypeMap.put(Double.class, double.class);
        primitiveWrapperTypeMap.put(Float.class, float.class);
        primitiveWrapperTypeMap.put(Integer.class, int.class);
        primitiveWrapperTypeMap.put(Long.class, long.class);
        primitiveWrapperTypeMap.put(Short.class, short.class);
    }


    public static boolean isAssignable(Class<?> targetType, Class valueType) {
        AssertInternal.notNull(targetType, "Target type must not be null");
        AssertInternal.notNull(valueType, "Value type must not be null");
        return (targetType.isAssignableFrom(valueType) || targetType
                .equals(primitiveWrapperTypeMap.get(valueType)));
    }


    public static List<Class<?>> typesForArgsAsList(final Object... args) {
        final List<Class<?>> classes = new ArrayList<Class<?>>();
        for (final Object arg : args) {
            if (args != null) {
                classes.add(arg.getClass());
            } else {
                classes.add(null);
            }
        }
        return classes;
    }

    public static Class[] typesForArgs(final Object... args) {
        return typesForArgsAsList(args).toArray(new Class[args.length]);
    }

    public static Class<?> forName(final String className) {
        final Class<?> clazz;
        try {
            clazz = Class.forName(className);
        } catch (final ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return clazz;
    }

}
